package models

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"strings"
	"time"
)

const UPerror  = "username or password error"
const Username = "admin"
const Password = "elco2020"
type User struct {
	UserName string
	PassWord string
}

type ResponseType struct {
	SuccessCode int
	MessageCode int
	Token string
}

func GetToken()(string, error)  {
	token:=jwt.New(jwt.SigningMethodHS256)
	claims:=make(jwt.MapClaims)
	claims["exp"]=time.Now().Add(1*time.Hour*time.Duration(1)).Unix()
	claims["iat"]=time.Now().Unix()
	token.Claims=claims

	tokenStr,err:=token.SignedString([]byte("sign"))
	if err!=nil{
		return "",err
	}else {
		return tokenStr,nil
	}
}

func Login(u User)(string,error)  {
	if u.UserName==Username&&u.PassWord==Password{
		token,err:=GetToken()
		if err!=nil{
			return  "",err
		}else {
			return  token,nil
		}
	}else {
		return "",errors.New(UPerror)
	}
}

func CheckToken(s string)(error)  {
	//if s=="null"{
	//	return errors.New("token is null")
	//}else{
	st:=strings.Split(s," ")
		if len(st)==1{
			return errors.New("token null")
		}else {
			s=st[1]
		token,err:=jwt.Parse(s, func(token *jwt.Token) (i interface{}, e error) {
			return []byte("sign"),nil
		})

		if err!=nil{
			return err
		}else {
			if token.Claims.Valid()!=nil{
				return err
			}else {
				return nil
			}
		}
	}
}